<?php

 //分析设计
 /*
权限粒度 ：一个按钮，一个页面，一个模块，并不是粒度越小越好，设计就越复杂，易用性就打折
          一般来说，对于后台控制，一般是按照模块来分权限
          权限名称是根据左侧栏的模块进行管理

          用户->角色->权限
          PS：一个用户拥有多个角色，一个角色也属于多个用户，权限和角色的关系也是如此 多对多的关系必然有一个关联表
          表设计：
          用户表users： id name password
          角色表roles:   id name description
          权限表permissions： id name description
          用户角色表role_user：id user_id role_id
          权限角色表role_permission：id role_id permission_id
 */

//路由
 /*
 //管理人员模块
 Route::get('/users','UserController@index');
 Route::get('/users/create','UserController@create');
 Route::post('/users/store','UserController@store');
 Route::get('/users/{user}/role','RoleController@role');
 Route::post('/users/{user}/role','RoleController@storeRole');
 //角色管理
 Route::get('/roles','RoleController@index');
 Route::get('/roles/create','RoleController@create');
 Route::post('/roles/store','RoleController@store');
 Route::get('/roles/{role}/permission','RoleController@permission');
 Route::post('/roles/{role}/permission','RoleController@storePermission');
 //权限管理
 Route::get('/permissions','PermissionController@index');
 Route::get('/permissions/create','PermissionController@create');
 Route::post('/permissions/store','PermissionController@store');
 */

 //模型关系
    /*
//user和role ，在user模型中
   用户有那些角色
       public function roles(){
       return $this->belongsToMany(Role::class,'admin_user_role','user_id','role_id')->withPivot(['user_id','role_id']);
     }
   用户是否有某个角色
   $roles是一个AdminRoles集合，判断当前拥有的角色和传进来的集合是否有交集，用intersect函数，！！作用是把数值转换成布尔类型0是false,非0是true;
       public function isInRoles($roles){
          return !!$roles->intersect($this->roles)->count();
     }
   用户是否有某个权限,只要判断这个用户拥有的角色是否和有这个角色拥有的权限是否有交集
       public function hasPermission($permission){
        return $this->isInRoles($permission->roles)
     }
   给用户分配角色
       public function assignRole($role){
        return  $this->roles()->save($role)
       }
   删除某个用户的角色
     public function deleteRole($role){
      return $this->roles()->detach($role);
   }
//role和permission，在role模型中
   当前角色的所有权限
       public function permissions(){
       return $this->belongsToMany(Permission::class,'admin_role_permission','role_id','permission_id')->withPivot(['permission_id','role_id']);
     }
   给角色赋予权限
      public function assignPermission($permission){
      return $this->permission()->save($permission);
    }
   取消角色的权限
     public function detelePermission($permission){
     return $this->permission()->detach($permission);
   }
   角色是否有权限 contains方法相当于in_array,比较两个集合，看看$permission是否在permissions集合中
     public function hasPermission($permission){
    return $this->permissions->contains($permission);
   }

//permission模型中
    public function roles(){
    return $this->belongsToMany(Role::class,'admin_role_permission','permission_id','role_id')->withPivot(['permission_id','role_id']);
    }
    */




//控制器中，无非就是CRUD,用户部分
class UserController extends Controller
{
    /*
     * 用户列表
     */
    public function index()
    {
        $users = \App\AdminUser::paginate(10);
        return view('/admin/user/index', compact('users'));
    }

    /*
     * 创建用户
     */
    public function create()
    {
        return view('/admin/user/add');
    }

    /*
     * 创建用户
     */
    public function store()
    {
        $this->validate(request(), [
            'name' => 'required|min:3',
            'password' => 'required'
        ]);

        $name = request('name');
        $password = bcrypt(request('password'));
        \App\AdminUser::create(compact('name', 'password'));
        return redirect('/admin/users');
    }

    /*
     * 角色的权限
     */
    public function role(\App\AdminUser $user)
    {
        //获取全部的角色
        $roles = \App\AdminRole::all();
        //获取当前用户拥有的角色
        $myRoles = $user->roles;
        return view('/admin/user/role', compact('roles', 'myRoles', 'user'));
    }

    /*
     * 保存权限
     */
    public function storeRole(\App\AdminUser $user)
    {
        //传递上来的roles
        $this->validate(request(),[
            'roles' => 'required|array'
        ]);
        //通过传递上来的roles id,获取roles的对象
        $roles = \App\AdminRole::find(request('roles'));
        //获取当前用户已经有的权限
        $myRoles = $user->roles;

        // 对已经有的权限进行更新,重复的删除，没有的就增加
        $addRoles = $roles->diff($myRoles);
        foreach ($addRoles as $role) {
            $user->assignRole($role);
        }

        $deleteRoles = $myRoles->diff($roles);
        foreach ($deleteRoles as $role) {
            $user->deleteRole($role);
        }
        return back();
    }
}

//用户角色视图
<form action="/admin/users/{{$user->id}}/role" method="POST">
        {{csrf_field()}}
        <div class="form-group">
            @foreach($roles as $role)
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="roles[]"
                                @if ($myRoles->contains($role))
                                checked
                                @endif
                                value="{{$role->id}}">
                        {{$role->name}}
                    </label>
                </div>
            @endforeach
        </div>
        <div class="box-footer">
            <button type="submit" class="btn btn-primary">提交</button>
        </div>
</form>


//角色控制器中
class RoleController extends Controller
{
    /*
     * 用户列表
     */
    public function index()
    {
        $roles = \App\AdminRole::paginate(10);
        return view('/admin/role/index', compact('roles'));
    }

    /*
     * 创建角色
     */
    public function create()
    {
        return view('/admin/role/add');
    }

    /*
     * 创建角色
     */
    public function store()
    {
        $this->validate(request(), [
            'name' => 'required|min:3',
            'description' => 'required',
        ]);

        \App\AdminRole::create(request(['name', 'description']));
        return redirect('/admin/roles');
    }

    /*
     * 角色的权限
     */
    public function permission(\App\AdminRole $role)
    {
        //获取全部角色
        $permissions = \App\AdminPermission::all();
        //获取当前角色拥有的权限
        $myPermissions = $role->permissions;
        return view('/admin/role/permission', compact('permissions', 'myPermissions', 'role'));
    }

    /*
     * 保存权限
     */
    public function storePermission(\App\AdminRole $role)
    {
        $this->validate(request(),[
           'permissions' => 'required|array'
        ]);

        $permissions = \App\AdminPermission::findMary(request('permissions'));
        $myPermissions = $role->permissions;

        // 对已经有的权限
        $addPermissions = $permissions->diff($myPermissions);
        foreach ($addPermissions as $permission) {
            $role->grantPermission($permission);
        }

        $deletePermissions = $myPermissions->diff($permissions);
        foreach ($deletePermissions as $permission) {
            $role->deletePermission($permission);
        }
        return back();
    }

}

//角色权限视图
  <div class="box-header with-border">
                        <h3 class="box-title">权限列表</h3>
                    </div>
                    <!-- /.box-header -->
                    <div class="box-body">
                        <form action="/admin/roles/{{$role->id}}/permission" method="POST">
                            {{csrf_field()}}
                            <div class="form-group">
                                @foreach($permissions as $permission)
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="permissions[]"
                                                   @if ($myPermissions->contains($permission))
                                                   checked
                                                   @endif
                                                   value="{{$permission->id}}">
                                            {{$permission->name}}
                                        </label>
                                    </div>
                                @endforeach
                            </div>
                            <div class="box-footer">
                                <button type="submit" class="btn btn-primary">提交</button>
                            </div>
                        </form>


//权限控制器中
class PermissionController extends Controller
{
    /*
     * 用户列表
     */
    public function index()
    {
        $permissions = \App\AdminPermission::paginate(10);
        return view('/admin/permission/index', compact('permissions'));
    }

    /*
     * 创建用户
     */
    public function create()
    {
        return view('/admin/permission/add');
    }

    /*
     * 创建用户
     */
    public function store()
    {
        $this->validate(request(), [
            'name' => 'required|min:3',
            'description' => 'required'
        ]);

        \App\AdminPermission::create(request(['name', 'description']));
        return redirect('/admin/permissions');
    }
}






